<template>
  <div>
    <n-space vertical size="large">
      <!-- 核心指标卡片 -->
      <n-grid :cols="4" :x-gap="16">
        <n-gi>
          <n-card :bordered="false" class="stat-card">
            <n-statistic label="志愿者总数" :value="statistics.volunteerCount || 0" class="stat-item">
              <template #prefix>
                <div class="stat-icon" style="background: linear-gradient(135deg, #18A058 0%, #2dce89 100%);">
                  <n-icon size="32" color="#fff"><PeopleOutline /></n-icon>
                </div>
              </template>
              <template #suffix>
                <n-text depth="3" style="font-size: 14px;">人</n-text>
              </template>
            </n-statistic>
            <n-divider style="margin: 12px 0;" />
            <n-text depth="3" style="font-size: 12px;">
              近7日新增 <n-text type="success">{{ statistics.recentVolunteerCount || 0 }}</n-text> 人
            </n-text>
          </n-card>
        </n-gi>
        
        <n-gi>
          <n-card :bordered="false" class="stat-card">
            <n-statistic label="活动总数" :value="statistics.activityCount || 0" class="stat-item">
              <template #prefix>
                <div class="stat-icon" style="background: linear-gradient(135deg, #2080f0 0%, #5bb5f7 100%);">
                  <n-icon size="32" color="#fff"><CalendarOutline /></n-icon>
                </div>
              </template>
              <template #suffix>
                <n-text depth="3" style="font-size: 14px;">个</n-text>
              </template>
            </n-statistic>
            <n-divider style="margin: 12px 0;" />
            <n-text depth="3" style="font-size: 12px;">
              近7日新增 <n-text type="info">{{ statistics.recentActivityCount || 0 }}</n-text> 个
            </n-text>
          </n-card>
        </n-gi>
        
        <n-gi>
          <n-card :bordered="false" class="stat-card">
            <n-statistic label="进行中的活动" :value="statistics.ongoingActivityCount || 0" class="stat-item">
              <template #prefix>
                <div class="stat-icon" style="background: linear-gradient(135deg, #f0a020 0%, #ffb347 100%);">
                  <n-icon size="32" color="#fff"><TimeOutline /></n-icon>
                </div>
              </template>
              <template #suffix>
                <n-text depth="3" style="font-size: 14px;">个</n-text>
              </template>
            </n-statistic>
            <n-divider style="margin: 12px 0;" />
            <n-text depth="3" style="font-size: 12px;">
              活跃度 <n-text type="warning">{{ activityRate }}</n-text>
            </n-text>
          </n-card>
        </n-gi>
        
        <n-gi>
          <n-card :bordered="false" class="stat-card">
            <n-statistic label="累计积分" :value="statistics.totalPoints || 0" class="stat-item">
              <template #prefix>
                <div class="stat-icon" style="background: linear-gradient(135deg, #d03050 0%, #f78ca0 100%);">
                  <n-icon size="32" color="#fff"><TrophyOutline /></n-icon>
                </div>
              </template>
              <template #suffix>
                <n-text depth="3" style="font-size: 14px;">分</n-text>
              </template>
            </n-statistic>
            <n-divider style="margin: 12px 0;" />
            <n-text depth="3" style="font-size: 12px;">
              人均积分 <n-text type="error">{{ avgPoints }}</n-text>
            </n-text>
          </n-card>
        </n-gi>
      </n-grid>

      <!-- 图表区域 -->
      <n-grid :cols="2" :x-gap="16">
        <n-gi>
          <n-card title="志愿者增长趋势" :bordered="false">
            <div ref="volunteerChartRef" style="width: 100%; height: 320px;"></div>
          </n-card>
        </n-gi>
        
        <n-gi>
          <n-card title="活动类型分布" :bordered="false">
            <div ref="activityPieChartRef" style="width: 100%; height: 320px;"></div>
          </n-card>
        </n-gi>
      </n-grid>

      <n-grid :cols="2" :x-gap="16">
        <n-gi>
          <n-card title="月度活动统计" :bordered="false">
            <div ref="monthlyChartRef" style="width: 100%; height: 320px;"></div>
          </n-card>
        </n-gi>
        
        <n-gi>
          <n-card title="积分分布情况" :bordered="false">
            <div ref="pointsChartRef" style="width: 100%; height: 320px;"></div>
          </n-card>
        </n-gi>
      </n-grid>
    </n-space>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { getOverviewStatistics } from '@/api/statistics'
import { PeopleOutline, CalendarOutline, TimeOutline, TrophyOutline } from '@vicons/ionicons5'
import * as echarts from 'echarts'

const statistics = ref({})
const volunteerChartRef = ref(null)
const activityPieChartRef = ref(null)
const monthlyChartRef = ref(null)
const pointsChartRef = ref(null)

// 计算活跃度
const activityRate = computed(() => {
  if (!statistics.value.activityCount) return '0%'
  const rate = ((statistics.value.ongoingActivityCount || 0) / statistics.value.activityCount * 100).toFixed(1)
  return `${rate}%`
})

// 计算人均积分
const avgPoints = computed(() => {
  if (!statistics.value.volunteerCount) return 0
  return Math.round((statistics.value.totalPoints || 0) / statistics.value.volunteerCount)
})

// 初始化志愿者增长趋势图
const initVolunteerChart = () => {
  const chart = echarts.init(volunteerChartRef.value)
  
  // 模拟数据 - 最近7天
  const dates = []
  const values = []
  for (let i = 6; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    dates.push(`${date.getMonth() + 1}/${date.getDate()}`)
    values.push(Math.floor(Math.random() * 10) + (statistics.value.recentVolunteerCount || 0) / 7)
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      name: '新增志愿者',
      type: 'line',
      smooth: true,
      data: values,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
          offset: 0,
          color: 'rgba(24, 160, 88, 0.3)'
        }, {
          offset: 1,
          color: 'rgba(24, 160, 88, 0.05)'
        }])
      },
      itemStyle: {
        color: '#18A058'
      },
      lineStyle: {
        width: 2
      }
    }]
  }
  
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => chart.resize())
}

// 初始化活动类型分布图
const initActivityPieChart = () => {
  const chart = echarts.init(activityPieChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [{
      name: '活动类型',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 35, name: '环境保护', itemStyle: { color: '#18A058' } },
        { value: 28, name: '社区服务', itemStyle: { color: '#2080f0' } },
        { value: 20, name: '教育支持', itemStyle: { color: '#f0a020' } },
        { value: 12, name: '敬老助残', itemStyle: { color: '#d03050' } },
        { value: 5, name: '其他', itemStyle: { color: '#909399' } }
      ]
    }]
  }
  
  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 初始化月度活动统计图
const initMonthlyChart = () => {
  const chart = echarts.init(monthlyChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['活动数', '参与人次']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '活动数',
        type: 'bar',
        data: [12, 15, 18, 22, 25, 28, 30, 32, 35, 38, 40, 42],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            offset: 0,
            color: '#2080f0'
          }, {
            offset: 1,
            color: '#5bb5f7'
          }])
        }
      },
      {
        name: '参与人次',
        type: 'line',
        data: [120, 150, 180, 220, 250, 280, 300, 320, 350, 380, 400, 420],
        smooth: true,
        itemStyle: {
          color: '#18A058'
        }
      }
    ]
  }
  
  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 初始化积分分布图
const initPointsChart = () => {
  const chart = echarts.init(pointsChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['0-10分', '11-30分', '31-50分', '51-100分', '100分以上']
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [{
      name: '志愿者人数',
      type: 'bar',
      data: [5, 15, 25, 35, 20],
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
          offset: 0,
          color: '#d03050'
        }, {
          offset: 1,
          color: '#f78ca0'
        }]),
        borderRadius: [8, 8, 0, 0]
      }
    }]
  }
  
  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

const loadStatistics = async () => {
  try {
    const res = await getOverviewStatistics()
    statistics.value = res.data || {}
    
    // 等待DOM更新后初始化图表
    await nextTick()
    initVolunteerChart()
    initActivityPieChart()
    initMonthlyChart()
    initPointsChart()
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

onMounted(() => {
  loadStatistics()
})
</script>

<style scoped>
.stat-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.12);
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  margin-right: 16px;
}

:deep(.n-statistic__label) {
  font-size: 14px;
  color: #909399;
}

:deep(.n-statistic__value) {
  font-size: 28px;
  font-weight: 600;
}
</style>
